package cn.hxiong.ding.controller;

import cn.hxiong.ding.pojo.UserInfoBody;
import cn.hxiong.ding.pojo.UserInfoResult;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user")
@RestController
public class UserController {

    private final ObjectMapper objectMapper;

    public UserController(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @RequestMapping(path = "/getUserInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public UserInfoResult getUserInfo(@RequestParam(value = "code") String code) throws Exception {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            OapiV2UserGetuserinfoResponse response = client.execute(req, getAccessToken());
            if (response.isSuccess()) {
                String body = response.getBody();
                UserInfoBody userInfoResponse = objectMapper.readValue(body, UserInfoBody.class);
                return userInfoResponse.getResult();
            } else {
                throw new RuntimeException(response.getErrmsg());
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("get user info failed: %s", e.getMessage()));
        }
    }

    private com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    private String getAccessToken() throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("ding72v69a5jmyc67pzv")
                .setAppSecret("yw76gtQoCsXRU-_-gfkwnC-N5Div1sv6HEQxADXdkEEzT4BEa0DMgaRnjcoV3bqC");
        try {
            GetAccessTokenResponse response = client.getAccessToken(getAccessTokenRequest);
            return response.getBody().getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new RuntimeException(String.format("%s.%s", err.code, err.message));
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new RuntimeException(String.format("%s.%s", err.code, err.message));
            }
        }
        throw new RuntimeException("getAccessToken failed");
    }
}
